<template>
  <div class="add-employee">
    <div class="head">
        <div @click="$router.back()" class="back">
            <i class="icon el-icon-back"></i>
            <span>返回</span>
        </div>
        <div class="label">
            <span>{{ isEditStatus === false ? '添加员工信息' : '修改员工信息' }}</span>
        </div>
    </div>
    <div class="main">
        <el-form ref="ruleForm" :model="rulesData" :rules="rules">
            <el-form-item prop="username" label="账号：">
                <el-input v-model="rulesData.username" placeholder="请输入账号"></el-input>
            </el-form-item>
            <el-form-item prop="name" label="员工账号：">
                <el-input v-model="rulesData.name" placeholder="请输入员工姓名"></el-input>
            </el-form-item>
            <el-form-item prop="phone" label="手机号：">
                <el-input v-model="rulesData.phone" placeholder="请输入手机号"></el-input>
            </el-form-item>
            <el-form-item label="性别：">
                <el-radio v-model="sexRadio" label="男"></el-radio>
                <el-radio v-model="sexRadio" label="女"></el-radio>
            </el-form-item>
            <el-form-item prop="card" label="身份证号：">
                <el-input v-model="rulesData.card" placeholder="请输入身份证号"></el-input>
            </el-form-item>
        </el-form>
        <hr />
        <div class="operate">
            <el-button @click="$router.back()">取消</el-button>
            <el-button v-show="isEditStatus === true" type="primary"  @click="handleEditEmployee()" class="black">保存</el-button>
            <el-button v-show="isEditStatus === false" @click="handleEmployeeSave(false)" class="black">保存</el-button>
            <el-button v-show="isEditStatus === false" @click="handleEmployeeSave(true)" type="primary">保存并继续添加</el-button>
        </div>
    </div>
  </div>
</template>

<script>
import { addEmployee, getIdEmployee, editEmployee } from '@/api/employee'
export default {
  name: 'AddEmployee',
  data () {
    const validateUsername = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入账号'))
      }

      const reg = /^[a-zA-Z0-9]{3,20}$/
      if (!reg.test(value)) {
        callback(new Error('账号输入不符，请输入3-20个字符'))
      }
      callback()
    }
    const validateName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入员工姓名'))
      }

      const reg = /^[\u4e00-\u9fa5A-Za-z]+$/
      if (!reg.test(value)) {
        callback(new Error('员工姓名不能有特殊字符或数字'))
      }

      callback()
    }
    const validatePhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号'))
      }

      const reg = /^((\+|00)86)?1((3[\d])|(4[5,6,7,9])|(5[0-3,5-9])|(6[5-7])|(7[0-8])|(8[\d])|(9[1,8,9]))\d{8}$/
      if (!reg.test(value)) {
        callback(new Error('手机号格式不正确'))
      }

      callback()
    }
    const validateCard = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入身份证号'))
      }

      const reg = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][0-9])|10|20|30|31)\d{3}[\dXx]$/
      if (!reg.test(value)) {
        callback(new Error('身份证号格式不正确'))
      }

      callback()
    }
    return {
      sexRadio: '男',
      rulesData: {
        username: '',
        name: '',
        phone: '',
        card: ''
      },
      rules: {
        username: [
          { validator: validateUsername, required: true, trigger: 'blur' }
        ],
        name: [
          { validator: validateName, required: true, trigger: 'blur' }
        ],
        phone: [
          { validator: validatePhone, required: true, trigger: 'blur' }
        ],
        card: [
          { validator: validateCard, required: true, trigger: 'blur' }
        ]
      },
      isEditStatus: false,
      editEmployeeId: ''
    }
  },
  created () {
    if (this.$route.query.id) {
      this.isEditStatus = true
      this.getEmployeeDetails()
    }
  },
  methods: {
    handleEmployeeSave (isContinueSave) {
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) return
        try {
          const res = await addEmployee({
            idNumber: this.rulesData.card,
            name: this.rulesData.name,
            username: this.rulesData.username,
            phone: this.rulesData.phone,
            sex: this.sexRadio === '男' ? 1 : 0
          })
          if (res.code === 1) {
            this.$message.success('操作成功')
            isContinueSave || this.$router.back()
            this.$refs.ruleForm.resetFields()
          } else {
            this.$message.error(res.msg)
          }
        } catch (error) {
          this.$message.error(error.response.data.msg)
        }
      })
    },
    async getEmployeeDetails () {
      const res = await getIdEmployee(this.$route.query.id)
      if (res.code === 1) {
        this.editEmployeeId = res.data.id
        this.sexRadio = res.data.sex === 1 ? '男' : '女'
        this.rulesData.username = res.data.username
        this.rulesData.name = res.data.name
        this.rulesData.phone = res.data.phone
        this.rulesData.card = res.data.idNumber
      }
    },
    async handleEditEmployee () {
      try {
        const res = await editEmployee({
          id: this.editEmployeeId,
          idNumber: this.rulesData.card,
          name: this.rulesData.name,
          phone: this.rulesData.phone,
          sex: this.sexRadio,
          username: this.rulesData.username
        })
        if (res.code === 1) {
          this.$message.success('员工信息修改成功')
          this.$router.back()
        } else {
          this.$message.error(res.msg)
        }
      } catch (error) {
        this.$message.error(error.response.data.msg)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.head {
    display: flex;
    font-size: 16px;
    color: #333;
    opacity: 0;
    animation: opacity .5s ease-out .8s forwards;

    @keyframes opacity {
        0% {
            opacity: 0;
        }
        100% {
            opacity: 1;
        }
    }

    > div {
        display: flex;
        align-items: center;
    }

    .back {
        gap: 5px;
        padding-right: 10px;
        border-right: 1px solid #d8dde3;
        cursor: pointer;

        .icon {
            font-size: 18px;
            font-weight: 600;
        }
    }

    .label {
        padding-left: 10px;

        span {
            font-weight: 600;
        }
    }
}

.main {
    background-color: #fff;
    margin-top: 20px;
    padding: 20px;
    border-radius: 5px;

    ::v-deep .el-form {
        .el-form-item {
            display: flex;

            .el-form-item__label {
                width: 180px;
            }

            .el-input {
                width: 293px;
            }
        }
    }

    hr {
        margin: 20px 0;
        border: 0;
        width: 100%;
        height: 1px;
        background-color: #f3f4f7;
    }

    .operate {
        display: flex;
        justify-content: center;

        .el-button.black {
            background-color: #333;
            color: #fff;
            border-color: #333;
        }
    }
}
</style>
